package co.fitstart.coach.handler.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;

import co.fitstart.coach.handler.ImageHandler;
import co.fitstart.coach.handler.TencentHandler;
import co.fitstart.coach.handler.support.FileStorage;

/**
 * 
 * @author haiyan_xiao
 *
 */
@Component("imageHandler")
public class ImageHandlerImpl implements ImageHandler {
    private static final Logger logger = LoggerFactory.getLogger(ImageHandlerImpl.class);
    
    @Value("#{config['file.upload.path']}")
    private String uploadPath;
    
    @Value("#{config['contrast_photo.path']}")
    private String contrastPhotoPath;
    
    @Autowired
    private TencentHandler tencentHandler;
    
    /**
     * 
     */
    public Result saveImage(String mediaId, String imageName) {
        logger.info("saveImage() mediaId [{}]", mediaId);
        
        Result result = new Result();

        // get image inputstream from 
        InputStream inputStream = tencentHandler.downloadResource(mediaId);
        
        if(inputStream == null) {
            result.fail().message("图片上传失败");
            return result;
        }
        
        // save inputstream into file with floder and path
        FileStorage fileStorage = new FileStorage(contrastPhotoPath, imageName, "jpg");
        this.save(fileStorage, inputStream);
        
        result.success().data("fileName", fileStorage.getPath() + "/" + fileStorage.getFileName());
        return result;
    }
    
    /**
     * 
     * @param fileStorage
     * @param inputStream
     * @return
     */
    protected String save(FileStorage fileStorage, InputStream inputStream) {

        // 1. 新建文件 （新建文件名为系统指定文件名，扩展名为源文件扩展名， 路径为指定路径）
        File file = new File(this.uploadPath + fileStorage.getPath(), fileStorage.getFileName());
        
        // 2. 将字节流copy到新文件
        try {
            FileUtils.copyInputStreamToFile(inputStream, file);
        } catch (IOException e) {
            logger.error("#save() error");
            throw new BusinessException("文件存储失败");
        }
        
        // 3. 返回文件路径 + 文件名 + 扩展名
        return fileStorage.getFileName();
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.coach.handler.ImageHandler#deleteImage(java.lang.String, java.lang.String)
     */
    public void deleteImage(String roundCode, String suffix) {
        FileStorage fileStorage = new FileStorage(contrastPhotoPath, roundCode + "_" + suffix, "jpg");
        
        try {
            FileUtils.forceDeleteOnExit(new File(this.uploadPath + fileStorage.getPath(), fileStorage.getFileName()));
        } catch (IOException e) {
            logger.error("#delete() error");
            throw new BusinessException("文件删除失败");
        }
        
    }
}
